package com.lalawaimai.palteform.baselib.utils;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.Display;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 普通常用工具类
 * Created by WaterWood on 2018/5/29.
 */
public class CommonUtil {
    /**
     * 显示土司
     *
     * @param context
     * @param msg
     */
    public static void showToast(Context context, String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 获取状态栏高度——方法1
     */
    public static int getStateBarHeight(Context context) {
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = context.getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight1;
    }

    /**
     * dp转px
     *
     * @param dpval
     * @return
     */
    public static int dp2px(Context context, int dpval) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpval, context.getResources().getDisplayMetrics());
    }

    /**
     * 圆形等待提示框 无标题
     *
     * @param context 上下文对象
     * @param msg     提示内容
     * @return
     */
    public static ProgressDialog showProgressDialog(Context context, String msg) {
        return showProgressDialog(context, "", msg, ProgressDialog.STYLE_SPINNER);
    }

    /**
     * 圆形等待提示框
     *
     * @param context 上下文对象
     * @param title   标题
     * @param msg     提示内容
     * @return
     */
    public static ProgressDialog showProgressDialog(Context context, String title, String msg) {
        return showProgressDialog(context, title, msg, ProgressDialog.STYLE_SPINNER);
    }

    /**
     * 等待提示框
     *
     * @param context 上下文对象
     * @param title   标题
     * @param msg     提示内容
     * @param style   显示样式
     *                ProgressDialog.STYLE_SPINNER为圆形不确定进度条
     *                ProgressDialog.STYLE_HORIZONTAL为条形进图条
     * @return
     */
    public static ProgressDialog showProgressDialog(Context context, String title, String msg, int style) {
        ProgressDialog progress = new ProgressDialog(context, ProgressDialog.THEME_HOLO_LIGHT);
        progress.setMax(100);
        progress.setMessage(msg);
        progress.setCanceledOnTouchOutside(false);
        progress.setCancelable(true);//对话框可以被 返回键 取消
        progress.setIndeterminate(false);

        if (!NullUtil.isStringEmpty(title)) progress.setTitle(title);

        switch (style) {
            case ProgressDialog.STYLE_SPINNER:
                progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                break;
            case ProgressDialog.STYLE_HORIZONTAL:
                progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                break;
        }
        return progress;
    }

    /**
     * 检查是否存在虚拟按键栏
     */
    public static boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        //这种方式一定要注意写法要正确，内部应该是通过反射去调用的。
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            // check override flag
            String sNavBarOverride = getNavBarOverride();
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else { // fallback
            if (Build.VERSION.SDK_INT >= 14) {
                return !ViewConfiguration.get(context).hasPermanentMenuKey();
            } else {
                return false;
            }
        }
    }

    /**
     * 判断虚拟按键栏是否重写
     */
    public static String getNavBarOverride() {
        String sNavBarOverride = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable e) {
            }
        }
        return sNavBarOverride;
    }

    /**
     * 获取 虚拟按键的高度
     */
    public static int getBottomStatusHeight(Context context) {
        int totalHeight = getDpi(context);

        int contentHeight = getWindowHeight(context);

        return totalHeight - contentHeight;
    }

    /**
     * 获取屏幕原始尺寸高度，包括虚拟功能键高度
     */
    public static int getDpi(Context context) {
        int dpi = 0;
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        @SuppressWarnings("rawtypes")
        Class c;
        try {
            c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, displayMetrics);
            dpi = displayMetrics.heightPixels;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dpi;
    }

    /**
     * 获取屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getWindowWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    /**
     * 获取屏幕高度
     *
     * @param context
     * @return
     */

    public static int getWindowHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 隐藏输入法
     *
     * @param paramContext
     * @param paramEditText
     */
    public static void hideSoftKeyboard(Context paramContext,
                                        EditText paramEditText) {
        ((InputMethodManager) paramContext
                .getSystemService(Context.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(paramEditText.getWindowToken(), 0);
    }

    /**
     * 显示输入法
     *
     * @param paramContext
     * @param paramEditText
     */
    public static void showSoftKeyborad(Context paramContext,
                                        EditText paramEditText) {
        ((InputMethodManager) paramContext
                .getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(
                paramEditText, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 打电话方法
     *
     * @param activity
     * @param phoneNumber
     */
    public static void callPhone(final Activity activity, final String phoneNumber) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(activity, Manifest.permission.CALL_PHONE);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CALL_PHONE},
                        100);
                return;
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                builder.setTitle("是否要拨打电话");
                builder.setMessage("立即拨打号码"+phoneNumber);
                builder.setPositiveButton("立即拨打", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        realCall(activity, phoneNumber);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                AlertDialog alertDialog = builder.create();
                alertDialog.show();
            }
        } else {
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("是否要拨打电话");
            builder.setMessage("立即拨打号码"+phoneNumber);
            builder.setPositiveButton("立即拨打", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    realCall(activity, phoneNumber);
                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            AlertDialog alertDialog = builder.create();
            alertDialog.show();
        }
    }

    /**
     * 真正执行拨打电话的方法
     * @param activity
     * @param phoneNumber
     */
    private static void realCall(Activity activity, String phoneNumber) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_CALL);
        Uri uri = Uri.parse("tel:" + phoneNumber);
        intent.setData(uri);
        activity.startActivity(intent);
    }

    /**
     * 存储数据
     * @param context 上下文
     * @param dataName 数据名称
     * @param dataContent 数据内容
     * @param type -- int,string,boolean  数据类型
     */
    public static void saveData(Context context,String dataName,Object dataContent,String type){
        SharedPreferences sps = context.getSharedPreferences("plateform",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sps.edit();
        if (type.equals("int")){
            editor.putInt(dataName, (int) dataContent);
        }else if (type.equals("string")){
            editor.putString(dataName, (String) dataContent);
        }else if (type.equals("boolean")){
            editor.putBoolean(dataName, (Boolean) dataContent);
        }
        editor.commit();
    }

    /**
     * 读取数据
     * @param context
     * @param dataName
     * @param type
     * @return
     */
    public static Object readData(Context context,String dataName,String type){
        SharedPreferences sps = context.getSharedPreferences("plateform",Context.MODE_PRIVATE);
        if (type.equals("int")){
            return sps.getInt(dataName,0);
        }else if (type.equals("string")){
            return sps.getString(dataName,"");
        }else if (type.equals("boolean")){
            return sps.getBoolean(dataName,false);
        }else {
            return null;
        }
    }

    /**
     * 判断应用是否开启状态
     * @param context
     * @param packageName
     * @return
     */
    public static boolean isRunningApp(Context context, String packageName) {
        boolean isAppRunning = false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(100);
        for (ActivityManager.RunningTaskInfo info : list) {
            if (info.topActivity.getPackageName().equals(packageName) && info.baseActivity.getPackageName().equals(packageName)) {
                isAppRunning = true;
                break;
            }
        }
        return isAppRunning;
    }
}
